function mog = mog_M_step(X, Q, mog)
% inputs X, the data matrix, Q, the corresponding re-
% sponsibilities, and MOG the current parameter values.
% The function returns the updated parameter values.
%
% 2012 Maarten Inja & Chiel Kooijman.


s = size(mog, 2);

for k = 1:s
    % calculate Nk
    Nk = sum(Q(:, k));

    % calculate new MU
    mog{k}.MU = (1/Nk) .* (sum(repmat(Q(:, k),1,2) .* X));
    % calculate new SIGMA
    sigma = zeros(2);
	 diff = (X - repmat(mog{k}.MU, size(X, 1), 1))';
    for n = 1:size(X, 1)
        dn = diff(:,n);
        sigma += Q(n, k) * (dn * dn')';
    end
    sigma /= Nk;
    if cond(sigma) < 10.^10
		 mog{k}.SIGMA = sigma;
	 end
    % calculate new PI
    mog{k}.PI = Nk/size(X, 1);
end
